<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="dialogVisible"
        @close="closeDialog"
        width="50%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                批量修改
            </div>
        </template>
        <el-scrollbar v-loading="loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + labelWidth / 2 + 'px)'"
            >
                <el-form
                    ref="formRef"
                    @submit.prevent=""
                    :model="formData"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="labelWidth + 'px'"
                >
                    <el-form-item label="选择要修改的字段">
                        <el-select
                            v-model="selectedFields"
                            multiple
                            placeholder="请选择要修改的字段"
                            style="width: 100%"
                        >
                            <el-option
                                v-for="field in availableFields"
                                :key="field.value"
                                :label="field.label"
                                :value="field.value"
                            />
                        </el-select>
                    </el-form-item>

                    <template v-for="field in selectedFields" :key="field">
                        <FormItem 
                            v-if="field === 'order_status'"
                            :label="t('order.order_status')" 
                            type="select" 
                            v-model="formData[field]" 
                            :input-attr="{ content: { '待付款': t('order.order_status 待付款'), '待发货': t('order.order_status 待发货'), '待收货': t('order.order_status 待收货') } }" 
                            :placeholder="t('Please select field', { field: t('order.order_status') })" 
                        />
                        <FormItem 
                            v-else-if="field === 'wul_time' || field === 'end_tuik_time'"
                            :label="t(`order.${field}`)" 
                            type="datetime" 
                            v-model="formData[field]" 
                            :placeholder="t('Please select field', { field: t(`order.${field}`) })" 
                        />
                        <FormItem 
                            v-else-if="['goods_price', 'num', 'youh_price'].includes(field)"
                            :label="t(`order.${field}`)" 
                            type="number" 
                            v-model="formData[field]" 
                            :input-attr="{ step: 1 }" 
                            :placeholder="t('Please input field', { field: t(`order.${field}`) })" 
                        />
                        <FormItem 
                            v-else-if="['image'].includes(field)"
                            :label="t(`order.${field}`)" 
                            type="image" 
                            v-model="formData[field]" 
  
                            :placeholder="t('Please input field', { field: t(`order.${field}`) })" 
                        />
                        <FormItem 
                            v-else
                            :label="t(`order.${field}`)" 
                            type="string" 
                            v-model="formData[field]" 
                            :placeholder="t('Please input field', { field: t(`order.${field}`) })" 
                        />
                    </template>
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + labelWidth / 1.8 + 'px)'">
                <el-button @click="closeDialog">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="submitLoading" @click="handleSubmit" type="primary">
                    {{ t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'

const config = useConfig()
const { t } = useI18n()

const props = defineProps<{
    baTable: baTableClass
    dialogVisible: boolean
}>()

const emit = defineEmits(['update:dialogVisible', 'success'])

const formRef = ref<FormInstance>()
const loading = ref(false)
const submitLoading = ref(false)
const labelWidth = 160

// 可选的字段
const availableFields = [
    { label: t('order.wul_name'), value: 'wul_name' },
    { label: t('order.wul_no'), value: 'wul_no' },
    { label: t('order.wul_status'), value: 'wul_status' },
    { label: t('order.wul_time'), value: 'wul_time' },
    { label: t('order.shouh_name'), value: 'shouh_name' },
    { label: t('order.shouh_phone'), value: 'shouh_phone' },
    { label: t('order.shouh_address'), value: 'shouh_address' },
    { label: t('order.order_status'), value: 'order_status' },
    { label: t('order.end_tuik_time'), value: 'end_tuik_time' },
    { label: t('order.goods_name'), value: 'goods_name' },
    { label: t('order.goods_sku'), value: 'goods_sku' },
    { label: t('order.goods_price'), value: 'goods_price' },
    { label: t('order.num'), value: 'num' },
    { label: t('order.youh_price'), value: 'youh_price' },
    { label: t('order.image'), value: 'image' }
]

const selectedFields = ref<string[]>([])
const formData = reactive<{[key: string]: any}>({})

const closeDialog = () => {
    emit('update:dialogVisible', false)
    selectedFields.value = []
    Object.keys(formData).forEach(key => delete formData[key])
}

const handleSubmit = async () => {
    if (selectedFields.value.length === 0) {
        ElMessage.warning('请至少选择一个要修改的字段')
        return
    }

    const selection = props.baTable.getSelectionIds()
    if (!selection.length) {
        ElMessage.warning('请选择要修改的数据')
        return
    }

    submitLoading.value = true
    try {
        const postData: {
            ids: number[],
            data: {[key: string]: any}
        } = {
            ids: selection,
            data: {}
        }
        
        selectedFields.value.forEach(field => {
            if (formData[field] !== undefined && formData[field] !== '') {
                postData.data[field] = formData[field]
            }
        })

        const res = await props.baTable.api.postData('batchEdit', postData)
        if (res.code === 1) {
            ElMessage.success('批量修改成功')
            emit('success')
            closeDialog()
        } else {
            ElMessage.error(res.msg || '批量修改失败')
        }
    } catch (error) {
        console.error(error)
        ElMessage.error('操作失败')
    } finally {
        submitLoading.value = false
    }
}
</script>

<style scoped lang="scss"></style> 